package com.siecom.hostservice;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.protobuf.InvalidProtocolBufferException;
import com.ivsign.android.IDCReader.IDCReadInterface;
import com.pos.api.Icc;
import com.pos.api.Mcr;
import com.pos.api.Pci;
import com.pos.api.Picc;
import com.pos.api.SM;
import com.pos.api.Sys;
import com.pos.emvcore.EmvCore;
import com.siecom.constconfig.ConstDefine;
import com.siecom.framework.device.SiecomTask;
import com.siecom.module.DeviceCallback;
import com.siecom.module.DeviceInterface;
import com.siecom.module.EmvCoreCallBackImpl;
import com.siecom.module.KeyBoardRunnable;
import com.siecom.nativelibs.NativeFunction;
import com.siecom.signaturepad.views.SignaturePad;
import com.siecom.tool.ByteTool;
import com.siecom.tool.ContextUtils;
import com.siecom.tool.ImageUnit;
import com.siecom.tool.LogUtil;
import com.siecom.transport.ConnectStatusCallback;
import com.siecom.transport.Distribution;
import com.siecom.transport.SiecomDevice;
import com.siecom.transport.bluetooth.BlueServer;
import com.siecom.transport.bluetooth.IosSerialServer;
import com.siecom.transport.usbport.UsbUtils.AccessoryCommunicator;
import com.siecom.transport.usbport.receiver.OpenAccessoryReceiver;
import com.siecom.transport.usbport.receiver.UsbDetachedReceiver;
import com.siecom.zhq.hostservice.R;
import com.skyfishjy.library.RippleBackground;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


public class MainActivity extends Activity implements UsbDetachedReceiver.UsbDetachedListener , OpenAccessoryReceiver.OpenAccessoryListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private UsbManager mUsbManager ;
    public static Context context;
    private static ImageView animeView;
    private static AlertDialog signaturePad = null;

    private int winScreenWidth = 0;
    private int winScreenHeight = 0;

    private RippleBackground rippleBackground;
    private static ImageView foundDevice;
    private ImageView centerBtn;


    private static TextView localNameView;
    private static TextView localAddressView;
    private static TextView remoteNameView;
    private static TextView remoteAddressView;
    private static TextView mTvVersion;

    private static final int idAnimeStart = 1;
    private static final int idAnimeStop = 2;
    private static final int SignaturePadStart = 3;
    private static final int SignaturePadStop = 4;
    private static final int insideCardStart = 5;
    private static final int insideCardStop = 6;
    private static final int swipeCardStart = 7;
    private static final int swipeCardStop = 8;
    private static final int nfcCardStart = 9;
    private static final int nfcCardStop = 10;
    private static final int inOneCardStart = 11;
    private static final int inOneCardStop = 12;
    private static final int fingerPrintStart = 13;
    private static final int fingerPrintStop = 14;
    private static final int keyBoardStart = 15;
    private static final int keyBoardStop = 16;
    private static final int keyBoardUpdate = 17;
    private static final int keyBoardLengthERR = 18;

    private static final int inputOne = 19;
    private static final int inputTwo = 20;
    private static final int inputThree = 21;
    private static final int inputfour = 22;
    private static final int inputfive = 23;
    private static final int showName = 24;
    private static final int disconnect = 25;
    public static final int animeStart = 26;
    public static final int updataAppProgress = 27;

    private Button mClearButton;
    private static Button mSaveButton;
    private static SignaturePad mSignaturePad;
    private static AlertDialog keyBoardDialog = null;
    private static EditText keyBoardText = null;
    private static String title;

    private static int passVoice = 0;
    private static TextView timeView,mTvHintMsg;

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    private static CountDownTimer countDownTimer;

    private static int outTime,colorRgb= 0x666666;
    private static String mHintMsg = "请签名";
    private static SoundPool soundPool;
    private static MediaPlayer mediaPlayer;

    private static HashMap<Integer, Integer> musicId = new HashMap<Integer, Integer>();

    private static volatile AnimationDrawable anim = null;

    public static void playSound(int speakerId) {

        mediaPlayer = MediaPlayer.create(context, speakerId);
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mediaPlayer.start();

    }

    public static void showKeyBoard() {

        animehandler.sendEmptyMessage(keyBoardStart);

    }

    public static void showKeyBoard(int passVoices) {
        passVoice = passVoices;
        animehandler.sendEmptyMessage(keyBoardStart);

    }

    public static void showInputOne() {

        animehandler.sendEmptyMessage(inputOne);

    }

    public static void showInputTwo() {

        animehandler.sendEmptyMessage(inputTwo);

    }

    public static void showInputThree() {

        animehandler.sendEmptyMessage(inputThree);

    }

    public static void showInputFour() {

        animehandler.sendEmptyMessage(inputfour);

    }

    public static void showInputFive() {

        animehandler.sendEmptyMessage(inputfive);

    }

    public static void keyBoardLengthERR() {
        animehandler.sendEmptyMessage(keyBoardLengthERR);
    }

    public static void closeKeyBoard() {
        animehandler.sendEmptyMessage(keyBoardStop);
    }

    public static void closeKeyBoard(String msg) {

        animehandler.sendEmptyMessage(keyBoardStop);
        animehandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void updateKeyBoard(int data) {
        Message message = new Message();
        message.what = keyBoardUpdate;
        Bundle bundle = new Bundle();
        bundle.putInt("data", data);
        message.setData(bundle);
        animehandler.sendMessage(message);
    }

    public static Bitmap getSignaturePadBitmap() {
        return mSignaturePad.getTransparentSignatureBitmap();
    }

    public static void startFingerPrint() {
        animehandler.sendEmptyMessage(fingerPrintStart);
    }

    public static void stopFingerPrint() {
        animehandler.sendEmptyMessage(fingerPrintStop);
    }

    public static void startInoneCard() {
        animehandler.sendEmptyMessage(inOneCardStart);
    }

    public static void stopInoneCard() {
        animehandler.sendEmptyMessage(inOneCardStop);
    }

    public static void startNfcCard() {
        animehandler.sendEmptyMessage(nfcCardStart);
    }

    public static void stopNfcCard() {
        animehandler.sendEmptyMessage(nfcCardStop);
    }

    public static void startSwipeCard() {
        animehandler.sendEmptyMessage(swipeCardStart);
    }

    public static void stopSwipeCard() {
        animehandler.sendEmptyMessage(swipeCardStop);
    }

    public static void startInsideCard() {
        animehandler.sendEmptyMessage(insideCardStart);
    }

    public static void stopInsideCard() {
        animehandler.sendEmptyMessage(insideCardStop);
    }

    public static void showSignaturePad(int time,String hintMsg,int color) {
        outTime = time;
        mHintMsg = hintMsg;
        colorRgb = color;
        animehandler.sendEmptyMessage(SignaturePadStart);

        startSignature();

    }

    public static void startSignature() {
       DeviceInterface.startSignature();
    }

    public static void clearSignature() {
       DeviceInterface.clearSignature();
    }

    public static void disconnectBlue(){
        animehandler.sendEmptyMessage(disconnect);
    }


    public  interface SignatureCallball{

        public void endSign(int res,byte[] data);

    }
    public static void endSignature(SignatureCallball callball) {


        DeviceInterface.endSignature(new DeviceCallback() {
            @Override
            public void onStart() {
                LogUtil.e(TAG,"endSignature " + " onStart ");
            }

            @Override
            public void onError(Bundle bundle) {
                int res = bundle.getInt("code");
                LogUtil.e(TAG,"endSignature " + " onError res = " + res);
                callball.endSign(res,null);
            }

            @Override
            public void onSuccess(Bundle bundle) {
                LogUtil.e(TAG,"endSignature " + " onSuccess ");
                callball.endSign(0x90,bundle.getByteArray("data"));
            }

            @Override
            public void onCompleted(Bundle bundle) {
                try{
                    Thread.sleep(400);
                }catch (Exception e) {
                }
                LogUtil.e(TAG,"endSignature " + " onCompleted ");
                callball.endSign(10086,null);
            }
        },false);

    }

    public static void closeSignature() {
       DeviceInterface.closeSignature();
    }

    public static void cancelSignaturePad() {
        animehandler.sendEmptyMessage(SignaturePadStop);
    }

    public static void startIDAnime() {
        animehandler.sendEmptyMessage(idAnimeStart);
    }

    public static void stopIDAnime() {
        animehandler.sendEmptyMessage(idAnimeStop);
    }

    public static void showUpdateAppProgress(Message msg){
        animehandler.sendMessage(msg);
    }
    public static Handler animehandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
//            Toast.makeText(context," ",Toast.LENGTH_SHORT).show();
            Runnable runnable;
            switch (msg.what) {
                case keyBoardLengthERR:
                    Toast.makeText(context, "密码长度不对，请继续输入", Toast.LENGTH_SHORT).show();
                    break;
                case keyBoardUpdate:
                    Bundle bundle = msg.getData();
                    int data = bundle.getInt("data");

                    if (keyBoardDialog != null && keyBoardDialog.isShowing()) {
                        keyBoardDialog.setTitle(title + "已经输入长度" + data);
                        if (keyBoardText != null) {
                            StringBuffer buf = new StringBuffer();

                            for (int i = 0; i < data; i++)
                                buf.append("*");

                            keyBoardText.setText(buf.toString());
                        }
                    }
                    break;
                case keyBoardStop:
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardDialog.dismiss();
                        keyBoardText = null;
//                        KeyBoardRunnable.unregisterPinEntryReceiver();//取消广播
                        LogUtil.e(TAG,"keyBoardStop -------------");
                    }
                    break;
                case keyBoardStart:
                    Toast.makeText(context,"请输入密码",Toast.LENGTH_SHORT).show();
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardDialog.dismiss();
                        keyBoardText = null;
                    }
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (passVoice == 0) {
                                soundPool.play(musicId.get(8), 1, 1, 0, 0, 1);
                            } else if (passVoice == 1) {
                                soundPool.play(musicId.get(10), 1, 1, 0, 0, 1);
                            } else if (passVoice == 2) {
                                soundPool.play(musicId.get(9), 1, 1, 0, 0, 1);
                            }
                        }
                    };

                    executorService.submit(runnable);

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle(R.string.inputPWD);
                    title = context.getResources().getString(R.string.inputPWD);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp1 = keyBoardDialog.getWindow().getAttributes();
                    lp1.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp1.height = ContextUtils.getScreenHeight(context) - 100; //设置宽度
                    lp1.dimAmount =0f;

                    keyBoardDialog.getWindow().setAttributes(lp1);
                    break;

                case inputOne: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputOne);
                    title = context.getResources().getString(R.string.inputOne);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);

                    break;
                }
                case inputTwo: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputTwo);
                    title = context.getResources().getString(R.string.inputTwo);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case inputThree: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputCop1);
                    title = context.getResources().getString(R.string.inputCop1);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case inputfour: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputCop2);
                    title = context.getResources().getString(R.string.inputCop2);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case inputfive: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputQuery);
                    title = context.getResources().getString(R.string.inputQuery);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case fingerPrintStart:
                    Toast.makeText(context,"读指纹",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(4), 1, 1, 0, 0, 1);
                        }
                    };
                    executorService.submit(runnable);
                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.fingerprint_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    break;
                case fingerPrintStop:
//                    Toast.makeText(context,"结束读指纹",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
//                            soundPool.play(musicId.get(11), 1, 1, 0, 0, 1);
                        }
                    };
                    executorService.submit(runnable);
                    animeView.setBackgroundResource(R.drawable.fingerprint_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
//                    if(DeviceInterface.fingerImage != null)
//                    animeView.setImageBitmap(DeviceInterface.fingerImage);
                    break;
                case inOneCardStart:
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(6), 1, 1, 0, 0, 1);
                        }
                    };

                    executorService.submit(runnable);


                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.inone_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();

                    break;
                case inOneCardStop:
                    animeView.setBackgroundResource(R.drawable.inone_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    break;
                case nfcCardStart:
                    Toast.makeText(context,"请放置NFC卡",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(3), 1, 1, 0, 0, 1);
                        }
                    };

                    executorService.submit(runnable);

                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.nfc_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    break;
                case nfcCardStop:
//                    Toast.makeText(context,"NFC",Toast.LENGTH_SHORT).show();
                    animeView.setBackgroundResource(R.drawable.nfc_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    break;
                case swipeCardStart:
                    Toast.makeText(context,"请刷卡",Toast.LENGTH_SHORT).show();

                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(5), 1, 1, 0, 0, 1);
                        }
                    };

                    executorService.submit(runnable);
                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.swipe_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    break;
                case swipeCardStop:
                    animeView.setBackgroundResource(R.drawable.swipe_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    break;
                case insideCardStop:
                    animeView.setBackgroundResource(R.drawable.inside_card_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    break;
                case insideCardStart:
                    Toast.makeText(context,"请插卡",Toast.LENGTH_SHORT).show();

                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(2), 1, 1, 0, 0, 1);
                        }
                    };

                    executorService.submit(runnable);
                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.inside_card_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    break;
                case idAnimeStart:
                    Toast.makeText(context,"读身份证",Toast.LENGTH_SHORT).show();

                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(1), 1, 1, 0, 0, 1);
                        }
                    };

                    executorService.submit(runnable);
                    animeView.setBackgroundResource(R.drawable.idanime);
                    animeView.setVisibility(View.VISIBLE);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    break;

                case idAnimeStop:
                    Toast.makeText(context,"结束读身份证",Toast.LENGTH_SHORT).show();
                    animeView.setBackgroundResource(R.drawable.idanime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    break;

                case SignaturePadStart:
                    Toast.makeText(context,"开始签名",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            soundPool.play(musicId.get(7), 1, 1, 0, 0, 1);
                        }
                    };

                    executorService.submit(runnable);
                    mTvHintMsg.setText(mHintMsg);
                    mTvHintMsg.setTextColor(colorRgb);
                    signaturePad.show();
                    WindowManager.LayoutParams lp = signaturePad.getWindow().getAttributes();
                    lp.width = ContextUtils.getScreenWidth(context); //设置宽度
                    lp.height = ContextUtils.getScreenHeight(context); //设置宽度
                    signaturePad.getWindow().setAttributes(lp);
                    startCountDown();

                    break;
                case SignaturePadStop:
                    if (signaturePad != null && signaturePad.isShowing())
                        signaturePad.cancel();
                    mSignaturePad.clear();
                    break;
                case showName:
                    Bundle bundle1 = msg.getData();
                    String name = bundle1.getString("data");
                    localNameView.setText(name);
                    LogUtil.e(TAG,"showName local=" + name);
                    localNameView.setVisibility(View.VISIBLE);
                    localAddressView.setText(BlueServer.getBTAddress());
                    localAddressView.setVisibility(View.VISIBLE);

                    break;
                case disconnect:
                    Toast.makeText(context, "外部连接设备已经断开连接", Toast.LENGTH_SHORT).show();
                    animeView.setVisibility(View.INVISIBLE);
                    remoteAddressView.setVisibility(View.INVISIBLE);
                    remoteNameView.setVisibility(View.INVISIBLE);
                    foundDevice.setVisibility(View.INVISIBLE);
                    // 0键盘  1指纹 2IC卡  3磁条卡  5蓝牙 6 身份证
                    MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)0);
                    break;
                case animeStart: {
                    Bundle bundle2 = msg.getData();
                    localNameView.setText(BlueServer.getName());
                    LogUtil.e(TAG,"animeStart =" + BlueServer.getName() );
                    localAddressView.setText(BlueServer.getBTAddress());
                    remoteNameView.setText(bundle2.getString("name"));
                    remoteAddressView.setText(bundle2.getString("address"));
                    localNameView.setVisibility(View.VISIBLE);
                    localAddressView.setVisibility(View.VISIBLE);
                    remoteNameView.setVisibility(View.VISIBLE);
                    remoteAddressView.setVisibility(View.VISIBLE);
                    Toast.makeText(context, "有外部设备连接", Toast.LENGTH_SHORT).show();
                    // 0键盘  1指纹 2IC卡  3磁条卡  5蓝牙 6 身份证
                    MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)1);
                    break;
                }

                case updataAppProgress:
                    Toast.makeText(context, "升级进度："+ msg.arg1 + "%", Toast.LENGTH_SHORT).show();
                    break;

            }

        }

    };
//    IosSerialServer mETServer = new IosSerialServer();
    public  static boolean isClean = true;
    int mWidth,mHeight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LogUtil.setDebug(true); //日志开关
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        context = this;

        winScreenWidth = ContextUtils.getScreenWidth(context);
        winScreenHeight = ContextUtils.getScreenHeight(context);
        Log.e("winScreenWidth:" + winScreenWidth, "winScreenHeight:" + winScreenHeight);
        // rippleBackground.startRippleAnimation();

        animeView = (ImageView) findViewById(R.id.anime);
        LayoutInflater inflater = LayoutInflater.from(this);

        rippleBackground = (RippleBackground) findViewById(R.id.content);
        foundDevice = (ImageView) findViewById(R.id.foundDevice);
        centerBtn = (ImageView) findViewById(R.id.centerImage);

        remoteNameView = (TextView) findViewById(R.id.remote_name);
        remoteAddressView = (TextView) findViewById(R.id.remote_address);

        localNameView = (TextView) findViewById(R.id.local_name);
        localAddressView = (TextView) findViewById(R.id.local_address);

        mTvVersion = findViewById(R.id.version_name);
        mTvVersion.setText("v " + getVersion() + ".");

        View layout = inflater.inflate(R.layout.signature_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        builder.setCancelable(false);

        signaturePad = builder.create();
        mSignaturePad = (SignaturePad) layout.findViewById(R.id.signature_pad);

        timeView = (TextView) layout.findViewById(R.id.timeView);
        mTvHintMsg = layout.findViewById(R.id.tvhintMsg);
        mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
            @Override
            public void onStartSigning() {

            }

            @Override
            public void onSigned() {
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
                isClean = false;
            }

            @Override
            public void onClear() {
//                mSaveButton.setEnabled(false);
//                mClearButton.setEnabled(false);
                isClean = true;
            }
        });

        mClearButton = (Button) layout.findViewById(R.id.clear_button);
        mSaveButton = (Button) layout.findViewById(R.id.save_button);

        mClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSignaturePad.clear();
                clearSignature();
            }
        });


        centerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });


        loadSound();
        initDevice();//设置了蓝牙名称

        initEmvReadCard();

        DeviceInterface.initSignPad();
        IntentFilter mScreenOnFilter = new IntentFilter("android.intent.action.SCREEN_ON");
        this.registerReceiver(mScreenOReceiver, mScreenOnFilter);
        /* 注册机器锁屏时的广播 */
        IntentFilter mScreenOffFilter = new IntentFilter("android.intent.action.SCREEN_OFF");
        this.registerReceiver(mScreenOReceiver, mScreenOffFilter);
        //电池状态监听广播
        IntentFilter mBattaryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        this.registerReceiver(mBatteryReceiver,mBattaryFilter);
        //初始化蓝牙
        this._bluetoothReceive = new BluetoothReciever();
        InitializeBluetoochAdapter();

        initUsbServer();
        setBluetoothBeDiscover();

//        mETServer.listenFromPort();
//        test();

        //临时测试需要指纹模块上电
//        DeviceInterface.InitFinger();

//        mTvVersion.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                Toast.makeText(context,"请写入SN号",Toast.LENGTH_SHORT).show();
//                showTestDialog();
//                return false;
//            }
//        });

        //写入SN号界面
//        showTestDialog();
//        IDCReadInterface.DLL_IDOpen();
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onStart() {
//        mETServer.listenFromPort();
//        LogUtil.e(TAG,"in = " + mETServer.mInputStream  + "---- out =" + mETServer.mOutputStream);
        super.onStart();
        IDCReadInterface.DLL_IDOpen();
        //---------------------------------------------------------------------

//        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
//            LogUtil.e(TAG,"BluetoothAdapter.getDefaultAdapter().isEnabled() = " + BluetoothAdapter.getDefaultAdapter().isEnabled());
//
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, 0);
//            finish();
//        }


        // ---------------------------------------------------------------------
    }

    @SuppressLint("MissingPermission")
    public void setBluetoothBeDiscover(){
        if(BluetoothAdapter.getDefaultAdapter().isEnabled()){
//            Intent intent1 = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//            intent1.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,30);
//            startActivityForResult(intent1,0);

            BLEperipheral.getBleInstance(context).initBle(); //初始化 BLE
//            IosSerialServer mETServer = new IosSerialServer();
//            mETServer.listenFromPort();
        }
    }

    AlertDialog dialog = null;
    //测试页面
    public void showTestDialog(){

        View layout = LayoutInflater.from(context).inflate(R.layout.dialog_test, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
        WindowManager.LayoutParams lp = signaturePad.getWindow().getAttributes();
        lp.width = ContextUtils.getScreenWidth(context); //设置宽度
        lp.height = ContextUtils.getScreenHeight(context); //设置宽度
        dialog.getWindow().setAttributes(lp);

        ImageView ivFront = layout.findViewById(R.id.iv_front);
        ImageView ivBack = layout.findViewById(R.id.iv_back);
        Button buttonRead = layout.findViewById(R.id.button_read_id);
        Button btnClear = layout.findViewById(R.id.btn_clear);

        EditText editText = layout.findViewById(R.id.et_in_sn_code);
        buttonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DeviceInterface.setSerialCode(editText.getText().toString().trim());
                    }
                }).start();

            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null != dialog && dialog.isShowing()){
                    dialog.dismiss();
                    dialog = null;
                }
            }
        });

    }


    public void test(){
//        byte[] bytes = ByteTool.hexStr2Bytes(ConstDefine.TEst_finger_data.replace(" ",""));
//        try {
//            LogUtil.e(TAG,"测试数据长度："+ bytes.length);
//            com.siecom.proto.Message.siecomproto msg = com.siecom.proto.Message.siecomproto.parseFrom(bytes);
//            LogUtil.e(TAG,"测试数据："+ msg.toString());
//        } catch (InvalidProtocolBufferException e) {
//            e.printStackTrace();
//        }
        String str = "02D1150000";
//        str = "02 D1 16 00 05 00 00 01 05 26";
        byte[] bytes = ByteTool.hexStr2Bytes(str.replace(" ",""));
        byte[] crcOut = new byte[2];
        NativeFunction.Crc16CCITT2(bytes,bytes.length  ,0,crcOut);
        LogUtil.e(TAG,"测试数据crcOut："+ ByteTool.byte2hex(crcOut));
    }


    private ExecutorService       mThreadPool;
    private OpenAccessoryReceiver mOpenAccessoryReceiver;
    private UsbDetachedReceiver mUsbDetachedReceiver;
    private static final String USB_ACTION               = "com.siecom.zhq.hostservice";
    private ParcelFileDescriptor mParcelFileDescriptor;
    private FileInputStream       mFileInputStream;
    private FileOutputStream      mFileOutputStream;
    private byte[]       mBytes        = new byte[1024];
    private StringBuffer mStringBuffer = new StringBuffer();

    public void initUsbServer(){
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mThreadPool = Executors.newFixedThreadPool(3);

        mUsbDetachedReceiver = new UsbDetachedReceiver(this);
        IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        registerReceiver(mUsbDetachedReceiver, filter);

        mOpenAccessoryReceiver = new OpenAccessoryReceiver(this);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(USB_ACTION), 0);
        IntentFilter intentFilter = new IntentFilter(USB_ACTION);
        registerReceiver(mOpenAccessoryReceiver, intentFilter);

        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        LogUtil.e(TAG ,"accessories==null? " +(accessories==null));
        UsbAccessory usbAccessory = (accessories == null ? null : accessories[0]);
//        Toast.makeText(MainActivity.context,"usbAccessory = null " + (usbAccessory==null) ,Toast.LENGTH_SHORT).show();
        if (usbAccessory != null) {
            LogUtil.e(TAG ,"usbAccessoryList=" +usbAccessory.toString());
//            if(!mUsbManager.hasPermission(usbAccessory)){
//                mUsbManager.requestPermission(usbAccessory, pendingIntent);
//            }
            Toast.makeText(MainActivity.context,"hasPermission " ,Toast.LENGTH_SHORT).show();
            if (mUsbManager.hasPermission(usbAccessory)) {
//                openAccessory(usbAccessory);
                LogUtil.e(TAG ,"已经拥有USB权限" );
                LogUtil.e(TAG ,"openAccessory" );
                SiecomDevice.startInitUsb(usbAccessory);
            } else {
                LogUtil.e(TAG ,"申请USB权限" );
                mUsbManager.requestPermission(usbAccessory, pendingIntent);
                LogUtil.e(TAG ,"申请USB权限 完成" );
            }
        }

//        UsbAccessory usbAccessory[] = mUsbManager.getAccessoryList();
//        LogUtil.e(TAG ,"usbAccessoryList=" +usbAccessory);
//        if(null != usbAccessory && usbAccessory.length > 0){
//            for(int i=0; i<usbAccessory.length ;i++){
//                UsbAccessory accessory = usbAccessory[i];
//                LogUtil.e(TAG ,"getDescription=" + accessory.getDescription());
//                LogUtil.e(TAG ,"getManufacturer=" + accessory.getManufacturer());
//                LogUtil.e(TAG ,"getModel=" + accessory.getModel());
//                LogUtil.e(TAG ,"getSerial=" + accessory.getSerial());
//                LogUtil.e(TAG ,"getUri=" + accessory.getUri());
//                LogUtil.e(TAG ,"getVersion=" + accessory.getVersion());
//            }
//        }
    }

    /**
     * 打开Accessory模式
     *
     * @param usbAccessory
     */
    private void openAccessory(UsbAccessory usbAccessory) {
        mParcelFileDescriptor = mUsbManager.openAccessory(usbAccessory);
        LogUtil.e(TAG,"mParcelFileDescriptor=" + mParcelFileDescriptor);

        if (mParcelFileDescriptor != null) {
            FileDescriptor fileDescriptor = mParcelFileDescriptor.getFileDescriptor();
            mFileInputStream = new FileInputStream(fileDescriptor);
            mFileOutputStream = new FileOutputStream(fileDescriptor);
            LogUtil.e(TAG,"连接成功！！！");
            Toast.makeText(this,"连接成功！！！" ,Toast.LENGTH_SHORT).show();

            mThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    int i = 0;
                    while (i >= 0) {
                        try {
                            LogUtil.e(TAG,"i==" + i);
                            i = mFileInputStream.read(mBytes);
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        }
                        if (i > 0) {
                            mStringBuffer.append(new String(mBytes, 0, i) + "\n");
//                            mHandler.sendEmptyMessage(RECEIVER_MESSAGE_SUCCESS);
                            LogUtil.e(TAG,"接收成功！！！" + new String(mBytes, 0, i));
//                            Toast.makeText(MainActivity.this,"接收成功：" + mStringBuffer.toString() ,Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
        }
    }

    /**
     * USB 连接
     */
    @Override
    public void usbDetached() {
        LogUtil.e(TAG,"usbDetached");
        Toast.makeText(this,"usbDetached" ,Toast.LENGTH_SHORT).show();
    }


    @Override
    public void openAccessoryModel(UsbAccessory usbAccessory) {
        LogUtil.e(TAG,"openAccessoryModel");
        Toast.makeText(this,"openAccessoryModel" ,Toast.LENGTH_SHORT).show();
        SiecomDevice.startInitUsb(usbAccessory);

    }

    @Override
    public void openAccessoryError() {
        LogUtil.e(TAG,"openDevicesError");
        Toast.makeText(this,"openDevicesError" ,Toast.LENGTH_SHORT).show();
    }


    private static EmvCore mMainEmvCore = null;
    private static Icc mMainIcc = null;
    private static Picc mMainPicc = null;
    private static Pci mMainPci = null; //密钥
    private static SM mSm = null; //国密
    private static Mcr mMcr ;
    private static Sys mSys = null;
    public static int miTransCount = 0;

    private EmvCoreCallBackImpl mEmvCoreCallBackImpl = null;
    public void initEmvReadCard(){
        mMainIcc = new Icc(MainActivity.this, new Icc.IccConnectStatusListener()
        {
            @Override
            public void onConnectResult(boolean bRet) {
                // TODO Auto-generated method stub
                System.out.println("Icc bRet: " + bRet);
                LogUtil.e(TAG,"ICC Ret:" + bRet);
            }

        });

        mMainPicc = new Picc(MainActivity.this, new Picc.PiccConnectStatusListener()
        {

            @Override
            public void onConnectResult(boolean bRet) {
                // TODO Auto-generated method stub
                System.out.println("Picc bRet: " + bRet);
                LogUtil.e(TAG,"Picc初始化 Ret:" + bRet);
            }

        });

        mMainPci = new Pci(MainActivity.this, new Pci.PciConnectStatusListener() {

            @Override
            public void onConnectResult(boolean bRet) {
                // TODO Auto-generated method stub
                LogUtil.e(TAG,"Pci初始化：" + bRet);
            }
        });

        mMcr = new Mcr(this, new Mcr.McrConnectStatusListener(){
            @Override
            public void onConnectResult(boolean bRet) {
                LogUtil.e(TAG,"Mcr初始化：" + bRet);
            }
        });
        //国密初始化
        mSm = new SM(context, new SM.SMConnectStatusListener() {
            @Override
            public void onConnectResult(boolean b) {
                LogUtil.e(TAG,"SM初始化：" + b);
            }
        });

        mSys = new Sys(context, new Sys.SysConnectStatusListener() {
            @Override
            public void onConnectResult(boolean bRet) {
            }
        });

        mEmvCoreCallBackImpl = new EmvCoreCallBackImpl(mMainIcc, mMainPicc, mMainPci);

        mMainEmvCore = new EmvCore();
        int iRet = -1;
        File fileDir = MainActivity.this.getFilesDir();

        String strPath = fileDir.getPath();
        strPath += "/EmvCore";
        iRet = mMainEmvCore.EmvLibInit(mEmvCoreCallBackImpl, strPath.getBytes(), strPath.getBytes().length);

        System.out.println("EmvLibInit iRet: " + iRet);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mWidth = mSignaturePad.getWidth();
        mHeight = mSignaturePad.getHeight();
        LogUtil.e("GJ","onWindowFocusChanged: width = " + mWidth + "   height = " + mHeight);
    }
//    private void initSignPad() {
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                dmtTest = new DmtSPIProcess();
//                /*****************************add by liubo Test SPI Reset****************************************/
////                dmtTest.Restore_SPI(102400);//if ret= 1003, Reset SPI
////                Log.e("initSignPad", "SPI Reset");
//                /***********************************Test SPI Reset End**********************************/
//                int res = dmtTest.connectDMTSignDM();
//                Log.e("initSignPad", "connectDMTSignDM--" + res);
//                if (res != DmtProtocol.STATUS_OK) {
//                    Log.e("connectDMTSignDM", "fail");
//                    return;
//                }
//                StringBuffer DevVer = new StringBuffer();
//                res = dmtTest.getversionDMTSignDM(DevVer);
//                if (res == DmtProtocol.STATUS_OK) {
//
//                    Log.e("getVer", "Ver:" + DevVer);
//
//                }
//                byte[] pubkey = new byte[64];
//                res = dmtTest.transSM2Publickey(0, pubkey);
//                Log.e("transSM2Publickey", res + "===");
//                String pukStr = ByteTool.byte2hex(pubkey);
//                if (res == DmtProtocol.STATUS_OK) {
//
//                    Log.e("pubkey", pukStr);
//
//                }
//                String cipher = SMUtil.SM2PubEncrypt(sm4key, pukStr.substring(0, 64),
//                        pukStr.substring(64, 128), 2);
//                Log.e("cipher", cipher);
//                byte[] verify = new byte[16];
//                res = dmtTest.setSM4PrimaryKey(ByteTool.hexStr2Bytes(cipher), verify);
//                Log.e("setSM4PrimaryKey", res + "==");
//                if (res == DmtProtocol.STATUS_OK) {
//                    Log.e("verify", ByteTool.byte2hex(verify));
//                }
//
//
//            }
//        };
//        executorThread.submit(runnable);
//
//    }

    private void loadSound() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (soundPool != null) {
                    soundPool.release();
                    soundPool = null;
                }
                soundPool = new SoundPool.Builder().setMaxStreams(15)
                        .build();
                musicId.put(1, soundPool.load(context, R.raw.idcard, 1));
                musicId.put(2, soundPool.load(context, R.raw.inside_card, 1));
                musicId.put(3, soundPool.load(context, R.raw.put_card, 1));
                musicId.put(4, soundPool.load(context, R.raw.qingluru, 1));
                musicId.put(5, soundPool.load(context, R.raw.swipe_card, 1));
                musicId.put(6, soundPool.load(context, R.raw.swipe_or_inside, 1));
                musicId.put(7, soundPool.load(context, R.raw.signature, 1));
                musicId.put(8, soundPool.load(context, R.raw.press_pwd, 1));
                musicId.put(9, soundPool.load(context, R.raw.errorpass, 1));
                musicId.put(10, soundPool.load(context, R.raw.againenter, 1));
                musicId.put(11, soundPool.load(context, R.raw.out_finger, 1));

                musicId.put(ConstDefine.OPERATE_SUCC, soundPool.load(context, R.raw.operate_success, 1));//
                musicId.put(ConstDefine.OPERATE_FAIL, soundPool.load(context, R.raw.operate_fail_pls_try_again, 1));

            }
        };
        executorService.submit(runnable);

    }

    public static void playVoice(int id){

        soundPool.autoPause();
        soundPool.play(musicId.get(id),1,1,0,0,1);
    }


    // 用广播接收器来更新蓝牙扫描的状态
    private class BluetoothReciever extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            LogUtil.e("=========================","蓝牙状态是："+action);
            switch (action){
                case "android.bluetooth.BluetoothAdapter.STATE_ON":
                case "android.bluetooth.adapter.action.STATE_CHANGED":

                    break;

                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:

                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    Log.e("bt","ACTION_DISCOVERY_FINISHED");

                    break;

            }

        }
    }

    private BluetoothReciever _bluetoothReceive = null;
    private void InitializeBluetoochAdapter() {

        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("android.bluetooth.device.action.FOUND");
        localIntentFilter
                .addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.SCAN_MODE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.device.action.PAIRING_REQUEST");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_STARTED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        localIntentFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
        localIntentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        localIntentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");

        this.registerReceiver(this._bluetoothReceive, localIntentFilter);

    }

    private BroadcastReceiver mScreenOReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals("android.intent.action.SCREEN_ON")) {

                Log.e("action", "SCREEN_ON");

//                Intent intent2 = new Intent(getApplicationContext(), MainActivity.class);
//                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                PendingIntent restartIntent = PendingIntent.getActivity(
//                        getApplicationContext(), 0, intent2, 0);
//
//                AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent);
//
//                // 关闭当前应用
//                HKBaseApplication.finishAllActivity();
//                HKBaseApplication.finishProgram();
//                System.gc();
//
////                loadSound();
////                Distribution.screeSwitch(true);
////                initDevice();


            } else if (action.equals("android.intent.action.SCREEN_OFF")) {

                Log.e("action", "SCREEN_OFF");
//                if (keyBoardDialog != null) {
//                    keyBoardDialog.cancel();
//                    keyBoardText = null;
//                }
//                DeviceInterface.lightOff();
//                Distribution.screeSwitch(false);
////                DeviceInterface.allClose();
//                SiecomDevice.closeBT();
//                SiecomDevice.closeSerial();
//                closeSignature();
//                localNameView.setVisibility(View.INVISIBLE);
//                localAddressView.setVisibility(View.INVISIBLE);
//                remoteAddressView.setVisibility(View.INVISIBLE);
//                remoteNameView.setVisibility(View.INVISIBLE);
            }else if(action.equals("com.pos.pinentry")){
                LogUtil.e("PinLen","PinLen:"+intent.getIntExtra("pinLen", 0));
            }
        }

    };
    public static JSONObject mBattaryInfoJB = new JSONObject();
    private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder();
            int rawlevel = intent.getIntExtra("level", -1);
            int scale = intent.getIntExtra("scale", -1);
            int status = intent.getIntExtra("status", -1);
            int health = intent.getIntExtra("health", -1);
            int level = -1;
            if(rawlevel >= 0 && scale > 0){
                level = (rawlevel*100)/scale;
            }
            sb.append("电池电量: ");
            sb.append(level + "%\n");

            String healthStatus = "";
            switch (health) {
                case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                    healthStatus = "UNKNOWN";
                    break;
                case BatteryManager.BATTERY_HEALTH_GOOD:
                    healthStatus = "GOOD";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                    healthStatus = "OVERHEAT";
                    break;
                case BatteryManager.BATTERY_HEALTH_DEAD:
                    healthStatus = "DEAD";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                    healthStatus = "OVER VOLTAGE";
                    break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                    healthStatus = "UNSPECIFIED FAILURE";
                    break;
                case BatteryManager.BATTERY_HEALTH_COLD:
                    healthStatus = "COLD";
                    break;

            }
            sb.append("健康度:" + healthStatus + "\n");
            int direction = -1;
            int isBatteryExist = 1;
            String batteryStatus ="";
            switch (status) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    batteryStatus="[没有安装电池]";
                    isBatteryExist = 0;
                    break;
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    batteryStatus="[正在充电]";
                    direction = 1;
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    batteryStatus="[已经充满]";
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    batteryStatus="[放电中]";
                    direction = 0;
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    batteryStatus="[未充电]";
                    break;
                default:
                    if(level <= 10)
                        sb.append("[电量过低，请充电]");
                    else if (level <= 100) {
                        sb.append("[未连接充电器]");
                    }
                    break;
            }
            sb.append(batteryStatus);
            LogUtil.d(TAG,"电池状态:" + sb.toString());
            try {
                mBattaryInfoJB.put("direction",direction); //充放电方向
                mBattaryInfoJB.put("isBatteryExist",isBatteryExist); //是否有电池
//                mBattaryInfoJB.put("electricity",level+"%"); //电量百分比
                mBattaryInfoJB.put("electricity",level); //电量百分比
                mBattaryInfoJB.put("code",0); //成功
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };
    public static void startCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
            timeView.setText("");

        }
        countDownTimer = new CountDownTimer(outTime, 1000) {

            @Override

            public void onTick(long millisUntilFinished) {

                // 倒计时中的方法
                timeView.setText(millisUntilFinished / 1000 + "秒");

            }

            @Override

            public void onFinish() {

                // 倒计时结束后的方法

                timeView.setText("");

            }

        };

        countDownTimer.start();

    }


    @Override
    protected void onResume() {
        LogUtil.e(TAG,"onResume");
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        MainActivity.getmMainPicc().DLL_PiccClose();
        Log.e("onStop", "onStop===");
//        IDCReadInterface.DLL_IDClose(); //关闭身份证
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy", "onDestroy");
//        DeviceInterface.allClose();
        closeSignature();
        unregisterReceiver(mScreenOReceiver);
        unregisterReceiver(mOpenAccessoryReceiver);
        unregisterReceiver(mUsbDetachedReceiver);
        unregisterReceiver(_bluetoothReceive);
        unregisterReceiver(mBatteryReceiver);
        if (mParcelFileDescriptor != null) {
            try {
                mParcelFileDescriptor.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mFileInputStream != null) {
            try {
                mFileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mFileOutputStream != null) {
            try {
                mFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 0键盘  1指纹 2IC卡  3磁条卡  5蓝牙 6 身份证
        MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)0);
        finish();
    }

    public static void setSignatureListener(View.OnClickListener listener) {

        mSaveButton.setOnClickListener(listener);

    }

    public static void showBlueName(String deviceName) {
        Message message = new Message();
        message.what = showName;
        Bundle bundle = new Bundle();
        bundle.putString("data", deviceName);
        message.setData(bundle);
        animehandler.sendMessage(message);

    }

    public static Observer<BluetoothSocket> observer = null;
    public void startServer() {
        LogUtil.e(TAG,"observer==null " + (observer==null));
        if(observer == null){
            observer = new Observer<BluetoothSocket>() {

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "蓝牙打开失败正在重试:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    //  CrashHandler.saveCrashInfo2File(e);
                    // DeviceInterface.allClose();
                }

                @Override
                public void onComplete() {

                    Log.e("accept", "Completed");

                }

                @Override
                public void onSubscribe(@NonNull Disposable disposable) {

                }

                @Override
                public void onNext(BluetoothSocket socket) {
                    LogUtil.e(TAG,"onNext onNext onNext");
                    /**
                     * 监听通讯状态
                     */
                    SiecomDevice.startListen(new ConnectStatusCallback() {
                        @Override
                        public void onConnectStart() {
                            Log.e("ConnectStatusCallback", "onConnectStart");
                        }

                        @Override
                        public void onConnected() {
                            Log.e("ConnectStatusCallback", "onConnected");
                            // 0键盘  1指纹 2IC卡  3磁条卡  5蓝牙 6 身份证
                            MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)1);
                        }

                        @Override
                        public void onDisConnect(Throwable e) {
                            // DeviceInterface.allClose();
                            Log.e("ConnectStatusCallback", e.getMessage());
                            animehandler.sendEmptyMessage(disconnect);

                            // 0键盘  1指纹 2IC卡  3磁条卡  5蓝牙 6 身份证
                            MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)0);
                        }
                    });

                    foundDevice();

                    rippleBackground.stopRippleAnimation();

                    com.siecom.framework.device.SiecomDevice.connectToBtDevice(null, new SiecomTask.TaskCallback() {
                        @Override
                        public void onStart(Bundle bundle) {

                        }

                        @Override
                        public void onSucceed(Bundle bundle) {
                            LogUtil.e(TAG,"connectToBtDevice onSucceed" );
                        }

                        @Override
                        public void onError(Bundle bundle) {
                            LogUtil.e(TAG,"connectToBtDevice onError" );
                        }
                    });

                    playAnimator();
                    Message message = new Message();
                    message.what = animeStart;
                    Bundle bundle = new Bundle();
                    bundle.putString("name", socket.getRemoteDevice().getName());
                    bundle.putString("address", socket.getRemoteDevice().getAddress());
                    message.setData(bundle);
                    animehandler.sendMessageDelayed(message, 1000);


                }
            };
        }

        SiecomDevice.initServer(observer, AndroidSchedulers.mainThread());


    }

    public void initDevice() {
        startServer();

//        Toast.makeText(context, "正在打开蓝牙", Toast.LENGTH_LONG).show();

//        if (!SiecomDevice.startSerial()) {
//
//            animehandler.post(new Runnable() {
//                @Override
//                public void run() {
//                    Toast.makeText(MainActivity.this, "外部通讯串口启动失败", Toast.LENGTH_SHORT).show();
//                }
//            });
//        }
//        DeviceInterface.allInit(new DeviceCallback() {
//            @Override
//            public void onStart() {
//
//
//            }
//
//            @Override
//            public void onError(Bundle bundle) {
//
//                if (!bundle.getBoolean("keyBoard")) {
//                    Toast.makeText(MainActivity.this, "键盘模块初始化失败", Toast.LENGTH_SHORT).show();
//                }
//                if (!bundle.getBoolean("finger")) {
//                    Toast.makeText(MainActivity.this, "指纹模块初始化失败", Toast.LENGTH_SHORT).show();
//                }
//                if (!bundle.getBoolean("finan")) {
//                    Toast.makeText(MainActivity.this, "金融模块初始化失败", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//
//            @Override
//            public void onSuccess(Bundle bundle) {
//
//
//            }
//
//            @Override
//            public void onCompleted(Bundle bundle) {
//                Log.e("onCompleted", "initDevice");
//
//                Toast.makeText(MainActivity.this, "所有模块正常启动", Toast.LENGTH_SHORT).show();
//
//                startServer();
//
//                Toast.makeText(context, "正在打开蓝牙", Toast.LENGTH_LONG).show();
//
//                if (!SiecomDevice.startSerial()) {
//
//                    animehandler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(MainActivity.this, "外部通讯串口启动失败", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
////                Runnable runnable = new Runnable() {
////                    @Override
////                    public void run() {
////
////                        String data = "0200702004c020c19a1116622424200000002119000000000001000020024905108106346224242000000021d29022015699031007353230313030303838393835323031353431313030303400594b503737584e424a3033323133353230313730383131373230383430202020202020202020202020202020203730303030303030323031373132233135366b0f432c4fa9d1cf260000000000000001649f26088534a124238358d09f101307010103a0a802010a01000000759593e938409f2701809f3704000000009f36020338950500800460009a031712069c01009f02060000000000015f2a02015682027c009f1a0201569f03060000000000009f3303e060c89f34034203009f3501229f1e085465726d696e616c8408a0000003330101029f090200029f4104000000019f63100000000000000000000000000000000000162200000000000050";
////                        byte[] buff = new byte[1024];
////                        int[] len = new int[1];
////                        CipherKeyBoardModule.getInstance().setEncryptKey("01","01");
////                        CipherKeyBoardModule.getInstance().getMacBD(ByteTool.hexStr2Bytes(data),buff,len);
////                        Log.e("buff",ByteTool.byte2hex(buff,0,len[0],false));
////                    }
////                };
////                new Thread(runnable).start();
//
//            }
//        });
    }



    private void foundDevice() {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(400);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        ArrayList<Animator> animatorList = new ArrayList<Animator>();
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(foundDevice, "ScaleX", 0f, 1.2f, 1f);
        animatorList.add(scaleXAnimator);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(foundDevice, "ScaleY", 0f, 1.2f, 1f);
        animatorList.add(scaleYAnimator);
        animatorSet.playTogether(animatorList);
        foundDevice.setVisibility(View.VISIBLE);
        animatorSet.start();
    }

    private void playAnimator() {
        float cx = centerBtn.getX();
        float cy = centerBtn.getY();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(centerBtn,
                "x", cx, 0f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(centerBtn,
                "y", cy, 0f);
        AnimatorSet animSet = new AnimatorSet();

        float x1 = foundDevice.getWidth();
        float y1 = foundDevice.getHeight();

        ObjectAnimator anim3 = ObjectAnimator.ofFloat(foundDevice,
                "x", foundDevice.getX(), winScreenWidth - x1);
        ObjectAnimator anim4 = ObjectAnimator.ofFloat(foundDevice,
                "y", foundDevice.getY(), winScreenHeight - y1);

        animSet.play(anim1).with(anim3);
        animSet.play(anim2).with(anim4);
        animSet.setDuration(1000);
        animSet.start();
    }



    public File getAlbumStorageDir(String albumName) {
        // Get the directory for the user's public pictures directory.
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), albumName);
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created");
        }
        return file;
    }

    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }


    private void scanMediaFile(File photo) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(photo);
        mediaScanIntent.setData(contentUri);
        MainActivity.this.sendBroadcast(mediaScanIntent);
    }
    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "无法获取到版本号";
        }
    }
    public boolean addSvgSignatureToGallery(String signatureSvg) {
        boolean result = false;
        try {
            File svgFile = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.svg", System.currentTimeMillis()));
            OutputStream stream = new FileOutputStream(svgFile);
            OutputStreamWriter writer = new OutputStreamWriter(stream);
            writer.write(signatureSvg);
            writer.close();
            stream.flush();
            stream.close();
            scanMediaFile(svgFile);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean addJpgSignatureToGallery(Bitmap signature) {
        boolean result = false;
        try {
            File photo = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.jpg", System.currentTimeMillis()));
            saveBitmapToJPG(signature, photo);
            scanMediaFile(photo);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Icc getmMainIcc(){
        return mMainIcc;
    }
    public static Picc getmMainPicc(){
        return mMainPicc;
    }
    public static Pci getmMainPci(){ return mMainPci; }
    public static Mcr getMainMcr(){
        return mMcr;
    }
    public static EmvCore getEmvCore()
    {
        return mMainEmvCore;
    }
    public static SM getmSm(){ return mSm;}
    public static Sys getmSys(){return mSys;}
}
